package logic

import (
	"context"
	"errors"
	"home/model/mysql"
	"home/pkg"

	"home/homerpc/homerpc"
	"home/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 手机号密码登录
func (l *LoginLogic) Login(in *homerpc.LoginRequest) (*homerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前用户不存在，请更换")
	}

	if user.Password != pkg.MD5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	return &homerpc.LoginResponse{
		Uid: int64(user.ID),
	}, nil
}
